<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.input.type" style="width: 160px">
            <el-option label="采购单号" value="purchase_no"></el-option>
            <el-option label="备料单号" value="plan_no"></el-option>
            <el-option label="合同单号" value="contract_no"></el-option>
            <el-option label="供应商名称" value="supplier_name"></el-option>
            <el-option label="采购单号/合同单号" value="purchase_no_contract_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.input.value" @search="query" class="w-60" />
        </VGroup>
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create style="min-width: 200px" multiple collapse-tags clearable filterable />
        <VSelect v-model="form.is_invoice" placeholder="是否开票" :options="options.is_invoice || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.doc_type" placeholder="合同类型" :options="options.doc_type || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.is_file" placeholder="供应商回执文件" :options="options.is_invoice || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.company_id" placeholder="公司主体" :options="options.company_id || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.enable" placeholder="是否作废" :options="options.is_invoice || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.download_count" placeholder="是否下载" :options="options.is_invoice || []" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="生成日期" value="create_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      <VSelect v-model="form.template_id" placeholder="合同模板" :options="options.template_id || []" multiple collapse-tags filterable clearable style="min-width: 160px" select/>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/manage/contract/pdf" :loading="loadings.pdf" @click="() => handleBatch('pdf', row)"><i class="dk-iconfont icon-Download" />批量下载pdf合同</VButton>
        <VButton auth="/purchase/manage/contract/excel" :loading="loadings.excel" @click="() => handleBatch('excel', row)"><i class="dk-iconfont icon-Download" />批量下载excel合同</VButton>
        <VButton auth="/purchase/manage/contract/download" :loading="loadings.download" @click="() => handleBatch('download', row)"><i class="dk-iconfont icon-Download" />下载回执合同
        </VButton>
        <VButton auth="/purchase/manage/contract/gpsr" :loading="loadings.gpsr" @click="() => handleBatch('gpsr', row)"><i class="dk-iconfont icon-Download" />批量下载GPSR标签
        </VButton>
        <VButton auth="/purchase/manage/contract/labelGpsr" :loading="loadings.labelGpsr" @click="() => handleBatch('labelGpsr', row)"><i class="dk-iconfont icon-Download" />批量下载合同及GPSR
        </VButton>
        <VButton auth="/purchase/manage/contract/cancel" :loading="loadings.download" @click="() => handleBatch('cancel', row)">批量作废</VButton>
        <VButton auth="/purchase/manage/contract/updateDelivery" :loading="loadings.download" @click="() => handleBatch('updateDelivery', row)">批量修改交期</VButton>
        <VExport auth="/purchase/manage/contract/export" mainKey="c_id" :name="baseName" :tableRef="tableRef" task class="ml-auto" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
    <Pdf ref="pdfRef" @success="query" />
    <Send ref="sendRef" @success="query" />
    <Upload ref="uploadRef" @success="query" />
    <UpdateDelivery ref="updateDeliveryRef" @success="query" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
  import api from './api'
  import Add from './components/Add'
  import Send from './components/Send'
  import Upload from './components/Upload'
  import UpdateDelivery from './components/UpdateDelivery'
  import Pdf from '@/views/settings/contract/components/Contract/Pdf'
  import { getOption } from '@/api/public'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { download, yesno } from '@/utils'
  import VXETable from 'vxe-table'
  import XEUtils from 'xe-utils'
  import { $auth } from "@/utils"
  import { resMessage } from '@/utils/res'
  const baseName = 'contract'
  const tableRef = ref()
  const loadings = reactive({})
  // 查询
  const query = () => {
    tableRef?.value.query()
  }

  // 添加
  const addRef = ref()

  // 获取options
  const options = ref({})
  Promise.all([
    getOption({ type: baseName }).then(res => res.data),
    getOption({ type: 'purchase' }).then(res => res.data),
    api.getTemplateOption().then(res => ({'template_id':res.data})),
    Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
  ]).then(res => {
    options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
  })

  // 批量操作
  const updateDeliveryRef = ref()
  const handleBatch = (name) => {
    const selection = tableRef.value.$table.getCheckboxRecords()
    if (!selection.length) {
      ElMessage.warning('请先选择行')
      return
    }
    const c_ids = selection.map(d => d.c_id)
    const showLoading = () => loadings[name] = true
    const closeLoading = () => loadings[name] = false
    const handle = {
      pdf: () => {
        showLoading('pdf')
        api.downloadCount({c_ids})
        pdfRef?.value.pdf(selection, {
          isLook: true,
          closeLoading
        })
      },
      gpsr: async() => {
        if([...new Set(selection.map(d => d.doc_type))].some(d => [2, 3].includes(d))) {
          ElMessage.error('非采购合同不能下载GPSR')
          return
        }
        showLoading()
        api.downloadLabel({c_ids, excel: 2}).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('文件下载完成后会发送到飞书账户！')
              query()
            }
          })
        }).finally(() => {
          closeLoading()
        })
        // const blob = await api.downloadLabel({c_ids, excel: 2})
        // VXETable.saveFile({ filename: `欧英代标签-${XEUtils.toDateString(new Date(), 'yyyyMMdd')}`, type: 'zip', content: blob })
        // closeLoading()
      },
      labelGpsr: async() => {
        if([...new Set(selection.map(d => d.doc_type))].some(d => [2, 3].includes(d))) {
          ElMessage.error('非采购合同不能下载GPSR')
          return
        }
        showLoading()
        api.downloadLabel({c_ids, excel: 1}).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('文件下载完成后会发送到飞书账户！')
              query()
            }
          })
        }).finally(() => {
          closeLoading()
        })
        // const blob = await api.downloadLabel({c_ids, excel: 1})
        // VXETable.saveFile({ filename: `欧英代标签-${XEUtils.toDateString(new Date(), 'yyyyMMdd')}`, type: 'zip', content: blob })
        // closeLoading()
      },
      excel: async () => {
        showLoading()
        api.downloadExcel({ c_ids }).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('文件下载完成后会发送到飞书账户！')
              query()
            }
          })
        }).finally(() => {
          closeLoading()
        })
        // for (const d of selection) {
        //   const {c_id} = d
        //   const blob = await api.downloadExcel({c_id})
        //   VXETable.saveFile({ filename: `${d.template_name}-${d.supplier_name}-${XEUtils.toDateString(new Date(), 'yyyyMMdd')}`, type: 'xlsx', content: blob })
        // }
        // closeLoading()
      },
      cancel: () => {
        ElMessageBox.confirm('是否确认作废？', '作废', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(() => {
            api.cancel({ c_ids }).then(res => {
              ElMessage({ type: 'success', message: '操作成功', })
              query()
            })
          })
          .catch(() => {
            ElMessage({ type: 'info', message: '取消操作', })
          })
      },
      download: async () => {
        const { yes } = yesno(selection, (d) => d.oss_url)
        if(!yes) return
        showLoading('download')
        await download(yes.map(d => d.oss_url), true)
        closeLoading('download')
      },
      updateDelivery: () => {
        updateDeliveryRef?.value.open(c_ids)
      }
    }
    handle[name]()
  }

  // 单行操作
  const logRef = ref()
  const pdfRef = ref()
  const sendRef = ref()
  const uploadRef = ref()
  const handleRow = (name, row, rowIndex) => {
    const { c_id } = row
    const showLoading = () => {
      loadings[name + rowIndex] = true
    }
    const closeLoading = () => {
      loadings[name + rowIndex] = false
    }
    const handle = {
      view: () => {
        showLoading()
        api.downloadCount({c_ids: [c_id]})
        pdfRef?.value.view(row, {
          isLook: true,
          closeLoading
        })
      },
      gpsr: async() => {
        showLoading()
        api.downloadLabel({c_ids: [c_id], excel: 2}).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('文件下载完成后会发送到飞书账户！')
              query()
            }
          })
        }).finally(() => {
          closeLoading()
        })
        // const blob = await api.downloadLabel({c_ids: [c_id], excel: 2})
        // VXETable.saveFile({ filename: `欧英代标签-${XEUtils.toDateString(new Date(), 'yyyyMMdd')}`, type: 'zip', content: blob })
        // closeLoading()
      },
      labelGpsr: async() => {
        showLoading()
        api.downloadLabel({c_ids: [c_id], excel: 1}).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('文件下载完成后会发送到飞书账户！')
              query()
            }
          })
        }).finally(() => {
          closeLoading()
        })
        // const blob = await api.downloadLabel({c_ids: [c_id], excel: 1})
        // VXETable.saveFile({ filename: `欧英代标签-${XEUtils.toDateString(new Date(), 'yyyyMMdd')}`, type: 'zip', content: blob })
        // closeLoading()
      },
      pdf: async() => {
        showLoading()
        api.downloadCount({c_ids: [c_id]})
        pdfRef?.value.pdf(row, {
          isLook: true,
          closeLoading
        })
      },
      excel: async() => {
        showLoading()
        api.downloadExcel({ c_ids:[c_id] }).then(res => {
          resMessage({
            res,
            success: () => {
              ElMessage.success('文件下载完成后会发送到飞书账户！')
              query()
            }
          })
        }).finally(() => {
          closeLoading()
        })
        // const blob = await api.downloadExcel({c_id})
        // VXETable.saveFile({ filename: `${row.template_name}-${row.supplier_name}-${XEUtils.toDateString(new Date(), 'yyyyMMdd')}`, type: 'xlsx', content: blob })
        // closeLoading()
      },
      edit: () => {
        showLoading()
        pdfRef?.value.pdf(row, {
          isLook: false,
          closeLoading
        })
      },
      cancel: () => {
        ElMessageBox.confirm('是否确认作废？', '作废', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(() => {
            api.cancel({ c_ids: [c_id] }).then(res => {
              ElMessage({ type: 'success', message: '操作成功', })
              query()
            })
          })
          .catch(() => {
            ElMessage({ type: 'info', message: '取消操作', })
          })
      },
      download: async () => {
        showLoading()
        await download([row.oss_url], true)
        closeLoading()
      },
      update: () => {
        showLoading('update')
        api.update({ c_id }).then(res => {
          ElMessage({ type: 'success', message: '操作成功', })
        }).finally(() => closeLoading('update'))
      },
      send: () => {
        sendRef?.value.open(c_id)
      },
      upload: () => {
        uploadRef?.value.open(c_id)
      },
      log: () => {
        logRef?.value.open({ log_type: baseName, c_id })
      },
    }
    handle[name]()
  }
  // 列表配置
  const totalMoney = ref({})
  const tableOptions = reactive({
    rowConfig: { height: 72 },
    showHeaderOverflow: false,
    formConfig: {
      data: {
        enable: [2],
        input: { type: 'purchase_no', value: '' },
        user: { type: 'purchase_user_id', value: [] },
        dateRange: { type: 'create_time', value: [], range: true },
      }
    },
    columns: [
      { type: 'checkbox', width: 40, fixed: 'left' },
      {
        title: '合同单号', field: 'contract_no', width: 240, slots: {
          default: ({ row }) => <div>
           <VText type="link" copy value={row.contract_no}>
            <el-link type='primary' onClick={() => handleRow('view', row)}>{row.contract_no}</el-link>
          </VText>
          </div>
        }
      },
      { title: '合同类型', field: 'doc_type_name', width: 100 },
      {
        title: '合同模板', field: 'template_name', width: 120, slots: {
          default: ({ row }) => <VText value={row.template_name} line={2} />
        }
      },
      {
        title: '来源单号', width: 150, slots: {
          default: ({ row, rowIndex }) => {
            const { source_no } = row
            if (!source_no?.length) return '-'
            const content = () => source_no.map(d => <div>{d}</div>)
            return <VMore value={content} line={2} key={rowIndex} />
          }
        }
      },
      {
        title: '采购人员', field: 'purchase_user', width: 140, slots: {
          default: ({ row }) => <VText value={row.purchase_user} />
        }
      },
      {
        title: '供应商名称', field: 'supplier_name', width: 140, slots: {
          default: ({ row }) => <VText value={row.supplier_name} line={2} />
        }
      },
      { title: '供应商id', field: 'supplier_code', width: 80 },
      {
        title: '公司主体', field: 'company_name', width: 140, slots: {
          default: ({ row }) => <VText value={row.company_name} line={2} />
        }
      },
      { title: '是否开票', field: 'is_invoice_name', width: 80 },
      {
        title: '生成时间', width: 170, slots: {
          default: ({ row }) => <div class='whitespace-pre-wrap'>{row.create_time}</div>
        }
      },
      { title: '是否作废', field: 'enable_name', width: 80 },
      { title: '下载次数', field: 'download_count', width: 80 },
      {
        title: '备注', field: 'remark', width: 120, slots: {
          default: ({ row }) => <VText value={row.remark} line={2} />
        }
      },
      {
        title: '供应商回执文件', width: 140, slots: {
          default: ({ row, rowIndex }) => {
            return row.oss_url ? <VButton auth="/purchase/manage/contract/downloadSupplier" link type="primary" onClick={() => handleRow('download', row, rowIndex)}>
              <a href={row.oss_url} target='_blank' download={row.oss_url.slice(row.oss_url.lastIndexOf('/') + 1)}>下载回执合同</a>
            </VButton> : '-'
          }
        }
      },
      {
        title: '操作', width: 130, fixed: 'right', slots: {
          default: ({ row, rowIndex }) => {
            const { return_status } = row
            // return_status	退货单状态 1待提交 2待审核 3待仓库处理 4已处理 5已驳回 6已作废
            const handles = [
              {label: '编辑合同模板', value: 'edit', attrs: {}},
              {label: '下载pdf合同', value: 'pdf', attrs: {}},
              {label: '下载excel合同', value: 'excel', attrs: {}},
              {label: '下载GPSR标签', value: 'gpsr', attrs: {disabled: row.doc_type !== 1}},
              {label: '下载合同及GPSR', value: 'labelGpsr', attrs: {disabled: row.doc_type !== 1}},
              {label: '上传回执合同', value: 'upload', attrs: {}},
              {label: '发送邮件', value: 'send', attrs: {}},
              {label: '作废', value: 'cancel', attrs: {}},
              {label: '更新', value: 'update', attrs: {}},
            ].filter(d => $auth(`/purchase/manage/contract/${d.value}`))
            return [<div class='nm flex flex-wrap gap-x-2 gap-y-0'>
              <el-dropdown trigger="click" placement="bottom-start" onCommand={name => handleRow(name, row, rowIndex)}>
                {{
                  default: () => <el-button link type='primary'>操作<i class="dk-iconfont icon-ArrowDown" /></el-button>,
                  dropdown: () => <el-dropdown-menu v-matomo>{handles.map(d => <el-dropdown-item command={d.value} {...d.attrs}>{d.label}</el-dropdown-item>)}</el-dropdown-menu>
                }}
              </el-dropdown>
              <VButton auth="/purchase/manage/contract/log" link type="primary" onClick={() => handleRow('log', row, rowIndex)}>日志</VButton>
            </div>]
          }
        }
      },
    ],
    proxyConfig: {
      autoLoad: false,
      ajax: {
        query: ({ page, form }) => api.query({ ...form, ...page }).then(res => {
          totalMoney.value = res.data.totalMoney
          return res
        })
      }
    }
  })
</script>
  